// pages/verify/verify.js
const host = require('../../config.js').host;
const network = require('../../utils/network.js');
// var wxCharts = require('../../utils/wxcharts.js');
import * as echarts from '../../components/ec-canvas/echarts.js';
var app = getApp();
var pieChart1 = null
var pieChart2 = null
var pieChart3 = null
Page({

  /**
   * 页面的初始数据
   */
  data: {
    host: host,
    phoneNum: '13663739801',
    password: '123456',
    TabCur: 0,
    TabItem: ["核销记录", "统计信息"],
    //核销列表
    prizeVerifyRecordList: [],
    //统计列表
    countList: [],
    pageSize: 5,
    pageNum: 1,
    isLoda: true,
    userType: -1, //用户类型
    verifyButtonShow: 0,// 核销按钮显示 0 否1 是

    merchantId: '',
    startDate: '',
    endDate: '',
    pie1: {
      onInit: function (canvas, width, height, dpr) {
        pieChart1 = echarts.init(canvas, null, {
          width: width,
          height: height,
          devicePixelRatio: dpr // new
        });
        canvas.setChart(pieChart1);
        return pieChart1;
      }
    },
    pie2: {
      onInit: function (canvas, width, height, dpr) {
        pieChart2 = echarts.init(canvas, null, {
          width: width,
          height: height,
          devicePixelRatio: dpr // new
        });
        canvas.setChart(pieChart2);
        return pieChart2;
      }
    },
    pie3: {
      onInit: function (canvas, width, height, dpr) {
        pieChart3 = echarts.init(canvas, null, {
          width: width,
          height: height,
          devicePixelRatio: dpr // new
        });
        canvas.setChart(pieChart3);
        return pieChart3;
      }
    },
  },

  touchHandler: function (e) {
    console.log(pieChart.getCurrentDataIndex(e));
  },

  //打开微信扫一扫跳转页面
  getScancode: function () {
    var _this = this;
    // 允许从相机和相册扫码
    wx.scanCode({
      success: (res) => {
        wx.navigateTo({
          url: '/pages/verifyresult/verifyresult?customerPrizeId=' + res.result
        })
        // 输出二维码值
        var result = res.result;
        _this.setData({
          result: result,
        })
      }
    })
  },

  toRank() {
    // 跳转页面到 确认核销页面
    wx.navigateTo({
      url: '/pages/verifyresult/verifyresult'
    })
  },

  tabSelect(e) {

    this.setData({
      TabCur: e.currentTarget.dataset.id,
      pageNum: 1
    })
    if (this.data.TabCur == 0) {
      //获取核销商品列表getprizeVerifyList
      this.getprizeVerifyList();
    } else {
      //获取统计信息列表
      this.getCountist();
      this.getStatistics();
    }

  },

  // 核销商品列表
  getprizeVerifyList() {

    network.requestGet("/xcx/prizeVerifyRecord/getMerchantList", {
      "pageNum": this.data.pageNum,
      "pageSize": 10

    }, res => {

      if (this.data.pageNum == 1) {
        this.setData({
          prizeVerifyRecordList: res.data.rows
        })
      } else {
        this.setData({
          prizeVerifyRecordList: this.data.prizeVerifyRecordList.concat(res.data.rows)
        })
      }

      if (res.data.rows.length < 10) {
        this.setData({
          isLoda: false
        })

      } else {
        this.setData({
          isLoda: true
        })

      }
    });
  },
  // 核销商品列表
  getCountist() {

    network.requestGet("/xcx/prizeVerifyRecord/getMerchantList", {
      "pageNum": this.data.pageNum,
      "pageSize": 10

    }, res => {

      if (this.data.pageNum == 1) {
        this.setData({
          countList: res.data.rows
        })
      } else {
        this.setData({
          countList: this.data.countList.concat(res.data.rows)
        })
      }

      if (res.data.rows.length < 10) {
        this.setData({
          isLoda: false
        })

      } else {
        this.setData({
          isLoda: true
        })

      }
    });
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let userInfo = getApp().globalData.userInfo;
    this.setData({
      userType: getApp().globalData.userType,
      merchantId: userInfo.id
    });
    // this.getdata();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {


  },

  getdata() {
    var windowWidth = 320;
    try {
      var res = wx.getSystemInfoSync();
      windowWidth = res.windowWidth;
    } catch (e) {
      console.error('getSystemInfoSync failed!');
    }
    pieChart1 = new wxCharts({
      animation: true,
      canvasId: 'pieCanvas1',
      type: 'pie',
      series: [{
        name: '成交量3',
        data: 78,
      }, {
        name: '成交量4',
        data: 63,
      }, {
        name: '成交量2',
        data: 35,
      }, {
        name: '成交量1',
        data: 15,
      }, {
        name: '成交量2',
        data: 35,
      }],
      width: windowWidth,
      height: 300,
      dataLabel: true,
    });
    pieChart2 = new wxCharts({
      animation: true,
      canvasId: 'pieCanvas2',
      type: 'pie',
      series: [{
        name: '成交量1',
        data: 15,
      }, {
        name: '成交量4',
        data: 63,
      }, {
        name: '成交量2',
        data: 35,
      }, {
        name: '成交量2',
        data: 35,
      }, {
        name: '成交量3',
        data: 78,
      }],
      width: windowWidth,
      height: 300,
      dataLabel: true,
    });
    pieChart3 = new wxCharts({
      animation: true,
      canvasId: 'pieCanvas3',
      type: 'pie',
      series: [{
        name: '成交量1',
        data: 15,
      }, {
        name: '成交量2',
        data: 35,
      }, {
        name: '成交量3',
        data: 78,
      }, {
        name: '成交量4',
        data: 63,
      }, {
        name: '成交量2',
        data: 35,
      }],
      width: windowWidth,
      height: 300,
      dataLabel: true,
    });
  },


  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let userInfo = getApp().globalData.userInfo;
    //  业主或顾客 不显示核销列表 0业主1商家2顾客3店员
    if (userInfo.userType == 0 || userInfo.userType == 2) {
      return;
    }
    if (userInfo.userType == 1) {
      // 3 
      this.setData({
        verifyButtonShow: 1,// 核销按钮显示
      })
    }
    if (userInfo.userType == 3) {
      // 当前登录的人是店员
      network.requestGet('/xcx/customer-relation/merchant-owner-list', {
        'relationType': '1', // 关联类型  1 商家绑店员
        'isBinding': '1', //  0 未绑定的/ 待绑定 1 已绑定
      }, res => {
        let resData = res.data.data;
        if (resData.length > 0) {
          this.setData({
            merchantId: resData[0].merchantId,
            verifyButtonShow: 1, // 说明有商家了
          })
        }
      })

    }


    //获取核销商品列表getprizeVerifyList
    this.getprizeVerifyList();

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    let page = this.data.pageNum + 1
    this.setData({
      pageNum: page
    })

    this.getprizeVerifyList()

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  getStatistics() {
    network.requestGet('/xcx/customer-prize/write-off-statistics', {
      "startTime": this.data.startDate,
      "endTime": this.data.endDate,
      "merchantId": this.data.merchantId
    }, res => {
      console.log("res", res);
      if (res.data.code == '200') {
        let statistics1 = res.data.data.statistics1;

        if(!res.data.data.statistics1 || res.data.data.statistics1.length < 1){
          let obj = {
            name: "暂无数据",
            value: 0
          }
          statistics1 = [obj];
        }
        let statistics2 = JSON.parse(JSON.stringify(res.data.data.statistics2));
        let statistics3 = JSON.parse(JSON.stringify(res.data.data.statistics2));
        if(res.data.data.statistics2 && res.data.data.statistics2.length > 0){
          for(let i in statistics2) {
            statistics2[i].name = statistics2[i].goodsName;
            statistics2[i].value = statistics2[i].count;
          }
          for(let i in statistics3) {
            statistics3[i].name = statistics3[i].goodsName;
            statistics3[i].value = statistics3[i].costPrice;
          }
        } else {
          let obj = {
            name: "暂无数据",
            value: 0
          }
          statistics2 = [obj];
          statistics3 = [obj];
        }
        //数据统计
        setTimeout(function(){
          pieChart1.setOption(getOption1(statistics1));
          pieChart2.setOption(getOption2(statistics2));
          pieChart3.setOption(getOption3(statistics3));
        }, 1000);
      } else {
        wx.showToast({
          title: res.data.msg,
          icon: 'none'
        })
      }
    })
  },
  StartDateChange(e){
    this.setData({
      startDate: e.detail.value
    })
    this.getStatistics();
  },
  EndDateChange(e){
    this.setData({
      endDate: e.detail.value
    })
    this.getStatistics();
  },
});

function getOption1(statistics1) {
  return {
    title: [{
      subtext: '统计不同活动的发放数',
        left: '50%',
        textAlign: 'center'
    }],
    series: [{
      label: {
        normal: {
          fontSize: 14
        }
      },
      itemStyle: {
        normal: {
          label: {
            show: true,
            formatter: '{b} : {c}'
            // formatter: '{b} : {c}'
          },
          labelLine: { show: true }
        }
      },
      type: 'pie',
      center: ['50%', '50%'],
      radius: ['40%', '60%'],
      data: statistics1
    }]
  };
}

function getOption2(data) {
  return {
    title: [{
      subtext: '统计不同活动的核销数量',
        left: '50%',
        textAlign: 'center'
    }],
    series: [{
      label: {
        normal: {
          fontSize: 14
        }
      },
      itemStyle: {
        normal: {
          label: {
            show: true,
            formatter: '{b} : {c}'
          },
          labelLine: { show: true }
        }
      },
      type: 'pie',
      center: ['50%', '50%'],
      radius: ['40%', '60%'],
      data: data
    }]
  };
}

function getOption3(data) {
  return {
    title: [{
      subtext: '统计不同活动的核销成本',
        left: '50%',
        textAlign: 'center'
    }],
    series: [{
      label: {
        normal: {
          fontSize: 14
        }
      },
      itemStyle: {
        normal: {
          label: {
            show: true,
            formatter: '{b} : {c}'
          },
          labelLine: { show: true }
        }
      },
      type: 'pie',
      center: ['50%', '50%'],
      radius: ['40%', '60%'],
      data: data
    }]
  };
}